using Microsoft.AspNetCore.Mvc;
using JTZY.Model.Product.Dto;
using JTZY.Model.Product;
using JTZY.Service.Product.IProductService;
using JTZY.Admin.WebApi.Filters;
using Microsoft.AspNetCore.Mvc.Routing;
using JTZY.Service.Goods.IGoodsService;
using JTZY.Service.Order.IOrderService;
using JTZY.Service.Business.IBusinessService;
using JTZY.Service.Business;

//创建时间：2024-12-03
namespace JTZY.Admin.WebApi.Controllers.Product
{
    /// <summary>
    /// 货物表
    /// </summary>
    [Verify]
    [Route("product/Prodinfo")]
    public class ProdinfoController : BaseController
    {
        /// <summary>
        /// 货物表接口
        /// </summary>
        private readonly IProdinfoService _ProdinfoService;
        private readonly IBillaftersaledetailService _billaftersaledetailService;
        private readonly ICorecmsuserstockService _usService;
        private readonly ICorecmsuserService _corecmsuserService;
        public ProdinfoController(IProdinfoService ProdinfoService
            , IBillaftersaledetailService billaftersaledetailService
            , ICorecmsuserService corecmsuserService
            , ICorecmsuserstockService usService)
        {
            _ProdinfoService = ProdinfoService;
            _usService = usService;
            _billaftersaledetailService = billaftersaledetailService;
            _corecmsuserService = corecmsuserService;
        }

        /// <summary>
        /// 查询货物表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "prodinfo:list")]
        public IActionResult QueryProdinfo([FromQuery] ProdinfoQueryDto parm)
        {
            parm.UserId= HttpContext.GetUId();
            var response = _ProdinfoService.GetList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询货物表详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("{Id}")]
        [ActionPermissionFilter(Permission = "prodinfo:query")]
        public IActionResult GetProdinfo(long Id)
        {
            var response = _ProdinfoService.GetInfo(Id);

            var info = response.Adapt<ProdinfoDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 查询货物表详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost("getprodinfobycode")]
        [ActionPermissionFilter(Permission = "prodinfo:query")]
        public IActionResult GetProdinfoByCode([FromBody] ProdQueryDto param)
        {
            var no = "";
            var f = "";
            if (string.IsNullOrEmpty(param.snCode))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "未检测到物码");

            }
            if (param.snCode.Contains("http"))
            {
                var Querys = UrlStringHelper.GetQueryDictionary(param.snCode);
                if (Querys.Keys.Contains("no"))
                    no = Querys["no"];
                if (Querys.Keys.Contains("n"))
                    no = Querys["n"];
                if (Querys.Keys.Contains("f"))
                    f = Querys["f"];
                //if (string.IsNullOrEmpty(f))
                //{
                //    f = "n";
                //}
                if (f.ToLower() != "w" && (param.type == "1" || param.type == "0" || param.type == "3"))
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "商品打包请扫盒子码");
                }
            }
            else
            {
                no = param.snCode;
            }
            var userId = HttpContext.GetUId();
            Prodinfo response = null;
            if (string.IsNullOrEmpty(f)) 
            {
                 response = _ProdinfoService.GetProdinfoByCode(no, "w");
                if (response == null)
                    response = _ProdinfoService.GetProdinfoByCode(no, "n");
            }
            else
            {
                 response = _ProdinfoService.GetProdinfoByCode(no, f);
            }
            if (param.type == "1" || param.type == "3")
            {

                if (response == null)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品未入库");
                }

                if (response != null && response.UserId.HasValue && response.UserId.Value > 0 && response.UserId != userId)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品不属于您");
                }

                //if (response.UserCusId.HasValue&& response.UserCusId>0 && param.type == "1")
                //{
                //    return ToResponse(ResultCode.CUSTOM_ERROR, "小仓商品，请调回本仓再操作");
                //}

                if (response.Status == 2)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已出库");
                }

                if (response.Status == 0)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品未入库");
                }

                if (response.IsReturn == 1)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已退库");
                }

                //var detail=_billaftersaledetailService.Queryable().Where(d => d.SnCode == no).First();
                //if (detail != null)
                //{
                //    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已出库");
                //}

            }

            if (param.type == "0" || param.type == "2")
            {
                if (response.Status == 1)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已入库，请勿重复");
                }
            }

            var info = response.Adapt<ProdinfoDto>();
            var prod = _usService.Queryable().Where(us => us.UserId == userId && us.ProductId == response.ProductId).First();
            decimal price = response.CostPrice ?? 0;
            if (param.UserId.HasValue)
            {
                var user = _corecmsuserService.GetById(param.UserId);
                if (user != null)
                {
                    switch (user.Level)
                    {
                        case "0":
                            price = prod.Vip0;
                            break;
                        case "1":
                            price = prod.Vip1;
                            break;                            
                        case "2":
                            price = prod.Vip2;
                            break;
                        case "3":
                            price = prod.Vip3;
                            break;
                        case "4":
                            price = prod.Vip4;
                            break;
                    }
                }
            }
            if (prod != null)
            {
                info.SkuImage = prod.SkuImage;
                info.SkuName = prod.SkuName;
                info.BarCode = prod.BarCode;
                info.Sn = prod.Sn;
                info.Price = price;
            }
            return SUCCESS(info);
        }

        /// <summary>
        /// 添加货物表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "prodinfo:add")]
        [Log(Title = "货物表", BusinessType = BusinessType.INSERT)]
        public IActionResult AddProdinfo([FromBody] ProdinfoDto parm)
        {
            var modal = parm.Adapt<Prodinfo>().ToCreate(HttpContext);

            var response = _ProdinfoService.AddProdinfo(modal);

            return SUCCESS(response);
        }

        /// <summary>
        /// 更新货物表
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "prodinfo:edit")]
        [Log(Title = "货物表", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateProdinfo([FromBody] ProdinfoDto parm)
        {
            var modal = parm.Adapt<Prodinfo>().ToUpdate(HttpContext);
            var response = _ProdinfoService.UpdateProdinfo(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除货物表
        /// </summary>
        /// <returns></returns>
        [HttpPost("delete/{ids}")]
        [ActionPermissionFilter(Permission = "prodinfo:delete")]
        [Log(Title = "货物表", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteProdinfo([FromRoute] string ids)
        {
            var idArr = Tools.SplitAndConvert<long>(ids);

            return ToResponse(_ProdinfoService.Delete(idArr));
        }

        [HttpGet("getorderdetail")]
        [ActionPermissionFilter(Permission = "prodinfo:query")]
        public IActionResult GetOrderDetail(string orderId)
        {
            var response = _ProdinfoService.GetDetail(orderId);

            //var info = response.Adapt<ProdinfoDto>();
            return SUCCESS(response);
        }

        [HttpGet("getafteretail")]
        [ActionPermissionFilter(Permission = "prodinfo:query")]
        public IActionResult GetAfterDetail(string aftersalesId)
        {
            var response = _ProdinfoService.GetAfterDetail(aftersalesId);

            return SUCCESS(response);
        }
    }
}